<template>
  <div class="my-header">
    <el-tabs v-model="data.activeName" class="demo-tabs">
      <el-tab-pane label="项目情况" name="first">
        <el-form :rules="rules" ref="ruleFormRef" :model="ruleForm" label-width="120px" class="demo-ruleForm" status-icon>
          <el-row>
            <el-col :span="8">
              <el-form-item label="项目名称" prop="projectname">
                <el-input placeholder="" v-model="ruleForm.projectname" maxlength="50"  show-word-limit clearable  />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目负责人" prop="joinpersons">
                <!-- <SelectOption :selectValue="ruleForm.joinpersonids" :options="options.userAllList"
                  @change-value="changeValue1"> </SelectOption> -->
                <user-list-modal
                  v-model="ruleForm.joinpersons"
                  @update:modelValue="changeValue1"
                  :default-users="[]"
                  :multiple="false"
                  :devType="'platform'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目编号" prop="projectsource">
                <el-input placeholder="" v-model="ruleForm.projectsource" maxlength="50"  show-word-limit clearable  />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="开始时间" prop="starttime">
                <el-date-picker v-model="ruleForm.starttime" type="date" placeholder="开始时间" format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD" style=" margin-right: 15px"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="结束时间" prop="endtime">
                <el-date-picker v-model="ruleForm.endtime" type="date" style=" margin-right: 15px" placeholder="结束时间"
                  format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="奖励标准" prop="incentivestandard">
                <SelectOption :selectValue="ruleForm.incentivestandard" :options="options.jlbzList"
                  @change-value="changeValue2"> </SelectOption>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="项目牵头单位">
                  <el-cascader :disabled="data.lobarDisabled" :options="data.selOp" :props="data.props" popper-class="gy-cascader"
                    style="width: 100%;" filterable="" ref="cascader" v-model="data.mainValue"  @change="chooseMatter"
                    placeholder="请选择" :show-all-levels="false">
                    <template #default="{ data }">
                      <el-tooltip
                      :disabled="data.name.length < 13"
                        class="item"
                        effect="dark"
                        :content="data.name"
                        placement="bottom-start"
                      >
                        <span>{{ data.name }}</span>
                      </el-tooltip>
                    </template>
                  </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="项目参研单位" >
                <el-cascader :disabled="data.lobarDisabled" :options="data.selOp" :props="data.props" popper-class="gy-cascader"
                  style="width: 100%;" filterable="" ref="cascader1" v-model="data.mainValue1" @change="chooseMatter1"
                  placeholder="请选择" :show-all-levels="false">
                    <template #default="{ data }">
                      <el-tooltip
                      :disabled="data.name.length < 13"
                        class="item"
                        effect="dark"
                        :content="data.name"
                        placement="bottom-start"
                      >
                        <span>{{ data.name }}</span>
                      </el-tooltip>
                    </template>
                </el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <el-tabs v-model="data.activeName" class="demo-tabs">
      <el-tab-pane label="奖项情况" name="first">

        <el-form :rules="rules" ref="ruleFormRef1" :model="ruleForm" label-width="120px" class="demo-ruleForm"
          status-icon>
          <el-row>
            <el-col :span="8">
              <el-form-item label="获奖级别" prop="awardlevel">
                <SelectOption :selectValue="ruleForm.awardlevel" :options="options.hjjbList" @change-value="changeValue3">
                </SelectOption>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="获奖类别" prop="awardwinning">
                <SelectOption :selectValue="ruleForm.awardwinning" :options="options.hjTypeList"
                  @change-value="changeValue4"> </SelectOption>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="获奖等级" prop="awardwinninglevel">
                <SelectOption :selectValue="ruleForm.awardwinninglevel" :options="options.hjdjList"
                  @change-value="changeValue5"> </SelectOption>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="获奖时间" prop="awardtime">
                <el-date-picker v-model="ruleForm.awardtime" type="date" placeholder="请选择" style=" margin-right: 15px"
                  format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="颁发单位" prop="issuingunit">
                <!-- <SelectOption :selectValue="ruleForm.issuingunit" :options="options.orgAllList"
                  @change-value="changeValue6"> </SelectOption> -->
                  <popup-tree-input
                  :data="data.selOp"
                  :props="data.popupTreeProps"
                  :prop="
                  deptForm.parentName == null
                  ? $t('message.org.top_menu')
                  : ruleForm.issuingunit
                  "
                  :node-key="'' + deptForm.parentId"
                  :current-change-handle="changeValue6"
                  />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="中咨集团排名" prop="groupranking">
                <SelectOption :selectValue="ruleForm.groupranking" :options="options.jtpmList"
                  @change-value="changeValue7"> </SelectOption>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <el-tabs v-model="data.activeName" class="demo-tabs">
      <el-tab-pane label="主要参加人员" name="first">
        <el-row style="padding-right: 50px;">
          <el-col >
            <Table :tableArr="usersList" :pagination="data.page" :columns="data.columns" :isCheckbox="true"
               :isSort="true">
              <template #operate="{ row }">
                <div >
                  <el-button size="small" class="ordinary" @click="deleteUser(row)">删除</el-button>
                </div>
             </template>
            </Table>
            <el-row>
              <el-col :span="8">
                <div style="margin:0 15px">
                  <!-- <SelectOption :selectValue="personForm.joinusername" :options="options.userAllList"
                    :placeholder="'请选择姓名'" @change-value="changeName"> </SelectOption> -->
                    <user-list-modal
                      v-model="personForm.joinusername"
                      @update:modelValue="changeName"
                      :default-users="[]"
                      :multiple="false"
                      :devType="'platform'"
                    />
                </div>
              </el-col>
              <el-col :span="8">
                <div style="margin:0 15px">
                  <!-- <SelectOption :selectValue="personForm.unit" :options="options.orgAllList" :placeholder="'请选择单位'"
                    @change-value="changeUnit"> </SelectOption> -->
                    <popup-tree-input
                    :data="data.selOp"
                    :props="data.popupTreeProps"
                    :prop="
                    deptForm.parentName == null
                    ? $t('message.org.top_menu')
                    : personForm.unit
                    "
                    :node-key="'' + deptForm.parentId"
                    :current-change-handle="changeUnit"
                    />
                </div>
              </el-col>
              <el-col :span="8">
                <div style="margin:0 15px">
                  <SelectOption :selectValue="personForm.role" :options="options.roleList" :placeholder="'请选择角色'"
                    @change-value="changeRole"> </SelectOption>
                </div>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="2">
            <el-button size="small" class="ordinary personAddBtn" @click="addPerson">添加</el-button>
          </el-col>
        </el-row>


      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<script lang="ts">
import { ref, reactive, computed, watch,watchEffect,onMounted, nextTick } from 'vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import Table from '@/views/science/components/table/table.vue'
import Api from '@/views/science/api/profess'
import { useStore } from 'vuex'
import { tips } from '@/views/science/components/tips/tips'
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue';
import * as proxy from "@/constants/proxy"
import request from "@/utils/request"
import UserListModal from '@/views/project/components/UserListModal/index.vue';
export default {
  components: {
    SelectOption,
    Table,
    PopupTreeInput,
    UserListModal,
  },
  emits: {
    usersChange: null,
    paramsChange: null,
    valueFlag2: null,
  },
  props: {
    fbData: {
      type: Object,
      required: true,
    },
    users: {
      type: Array,
      required: true,
    },
    addFlag: {
      type: Number,
      required: true,
    }
  },
  setup(props, { emit }) {
    const store = useStore()
    const labelPosition = ref('right')
    const data = reactive({
      activeName: ref('first'),
      dialogVisible: false,
      lobarDisabled: false,
      props: {
        checkStrictly : true,
        multiple: true,
        expandTrigger: 'hover',
        value: 'id',
        label: 'name',
        children: 'children',
        emitPath: false
      },
      mainValue: [] as any,
      mainValue1: [] as any,
      page: { page: 1, limit: 10, total: 0 },
      ids: [],
      params: {
        current: 1,
        id: "",
        name: "",
        size: 10
      },
      allTableData: [],
      columns: [
        {
          key: 'joinusername',
          width: 140,
          label: '姓名',
        },
        {
          key: 'unit',
          width: 140,
          label: '单位',
        },
        {
          key: 'role',
          width: 140,
          label: '担任角色',
        }
      ],
      selOp:[],
      popupTreeProps: {
        label: 'name',
        children: 'children',
      },
    })
    const deptForm = {
      parentId: 0,
      parentName: '',
    }

    // 弹窗中三个下拉选择
    let options = reactive({
      projectnameList: computed(() => store.state.technologyStrength.KJSL_DECLARATION_TYPE),
      unitnameList: computed(() => store.state.technologyStrength.KJSL_APPLYING_FOR_AWARDS1),

      orgAllList: computed(() => store.state.technologyStrength.orgAllList),
      userAllList: computed(() => store.state.technologyStrength.userAllList),
      roleList: computed(() => store.state.technologyStrength.roleList),
      projectSelect: computed(() => store.state.technologyStrength.projectSelect),
      // hjTypeList: computed(() => store.state.technologyStrength.KJSL_AWARD_CATEGORY),
      hjjbList: computed(() => store.state.technologyStrength.KHGL_KJSL_HJJB),
      hjTypeList: [],
      hjdjList: [],
      jlbzList: [
        {
          id: '1',
          itemText: '一等奖50万',
          itemValue: '1'
        },
        {
          id: '2',
          itemText: '二等奖30万',
          itemValue: '2'
        },
        {
          id: '3',
          itemText: '三等奖10万',
          itemValue: '3'
        }
      ],
      jtpmList: [
        {
          id: '1',
          itemText: '第一名',
          itemValue: '1'
        },
        {
          id: '2',
          itemText: '第二名',
          itemValue: '2'
        },
        {
          id: '3',
          itemText: '第三名',
          itemValue: '3'
        }
      ]
    })

    const getOrgList = () =>{
      return request({
        url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
        method: "get",
      }).then(res =>{
        data.selOp = res.data.data
      })
    }

    const pants = ref(props.fbData)

    const usersList = ref(props.users)

    // const ruleForm = reactive({
    //   id:'',
    //   awardApplyId: '1',
    //   projectId: "",
    //   projectname: "",
    //   joinpersonids: "",
    //   joinpersons: "",
    //   projectsource: "",
    //   classid: "",
    //   classname: "",
    //   competitionclassid: "",
    //   competitionclass: "",
    //   starttime: "",
    //   endtime: "",
    //   incentivestandardid: "",
    //   incentivestandard: "",
    //   awardlevelid: "",
    //   awardlevel: "",
    //   awardwinningid: "",
    //   awardwinning: "",
    //   awardwinninglevelid: "",
    //   awardwinninglevel: "",
    //   awardtime: "",
    //   issuingunitid: "",
    //   issuingunit: "",
    //   grouprankingid: "",
    //   groupranking: "",
    //   participantid: "",
    //   participant: "",
    //   participantunit: "",
    //   participantjs: "",
    // },)
    const ruleForm = reactive(store.state.technologyRewards.schedule)

    const handleData = (data) => {
      const arr1 = Object.keys(data || {})
      const list = ruleForm
      for (const key in list) {
        if (arr1.indexOf(key) !== -1) {
          list[key] = data[key]
        }
      }
      return list
    }

    const mainValueRef: any = ref([])
    const mainValueRef1: any = ref([])

    watch(props, (newValue, oldValue) => {
      // console.log('newValue',newValue)
      pants.value = newValue.fbData
      usersList.value = newValue.users
      Object.assign(ruleForm, handleData(newValue.fbData))
      // console.log('watchruleForm',newValue.fbData)

    },{deep:true});


    watch(() => props.addFlag,
        (newVal, oldVal) => {
          // console.log('watch',newVal)
          // console.log('watch fbData',props.fbData)
          pants.value = props.fbData
          usersList.value = props.users
          Object.assign(ruleForm, handleData(props.fbData))

          data.mainValue = ruleForm.classid.split(',')
          data.mainValue1 = ruleForm.competitionclassid.split(',')
        },{deep:true,immediate:true}
      )

    // const ruleForm = reactive(props.fbData)
    watch(ruleForm, (newValue, oldValue) => {
      emit('paramsChange', newValue)
    });

    watchEffect(() => {
      if (props.addFlag == 0) {
        console.log(124578)
        Object.keys(ruleForm).forEach((key) => {
          ruleForm[key] = ''
        })
        ruleForm.awardApplyId = '1'
      }
    })

    const changeValue = (item) => {
      ruleForm.projectname = item.projectname
      ruleForm.projectId = item.id
      // store.commit('technologyStrength/getachievementINFO', {
      //   ...{
      //     projectId: item.id,
      //   }
      // })
    }
    const changeValue1 = (item) => {
      ruleForm.joinpersons = item.cname
      ruleForm.joinpersonids = item.userId
    }
    const changeValue2 = (item) => {
      ruleForm.incentivestandard = item.itemText
      ruleForm.incentivestandardid = item.itemValue
    }
    const changeValue3 = (item) => {
      options.hjTypeList = item.children
      ruleForm.awardlevel = item.itemText
      ruleForm.awardlevelid = item.itemValue
    }

    const changeValue4 = (item) => {
      console.log(item)
      options.hjdjList = item.children
      ruleForm.awardwinning = item.itemText
      ruleForm.awardwinningid = item.itemValue
    }

    const changeValue5 = (item) => {
      ruleForm.awardwinninglevel = item.itemText
      ruleForm.awardwinninglevelid = item.itemValue
    }
    const changeValue6 = (item) => {
      ruleForm.issuingunit = item.name
      ruleForm.issuingunitid = item.id
    }
    const changeValue7 = (item) => {
      ruleForm.groupranking = item.itemText
      ruleForm.grouprankingid = item.itemValue
    }

    // 新增
    const rules = reactive({
      projectname: [
        { required: true, message: '请输入项目名称', trigger: 'change', },
      ],
      joinpersons: [
        { required: true, message: '请输入项目负责人', trigger: 'change', },
      ],
      projectsource: [
        { required: true, message: '请输入项目编号', trigger: 'change', },
      ],
      starttime: [
        { required: true, message: '请输入开始时间', trigger: 'blur' },
      ],
      endtime: [
        { required: true, message: '请输入结束时间', trigger: 'change', },
      ],
      incentivestandard: [
        { required: true, message: '请输入奖励标准', trigger: 'change', },
      ],
      classid: [
        { required: true, message: '请输入项目牵头单位', trigger: 'blur' },
      ],
      competitionclassid: [
        { required: true, message: '请输入项目参研单位', trigger: 'blur' },
      ],
      awardlevel: [
        { required: true, message: '请输入获奖级别', trigger: 'blur' },
      ],
      awardwinning: [
        { required: true, message: '请输入获奖类别', trigger: 'blur' },
      ],
      awardwinninglevel: [
        { required: true, message: '请输入获奖等级', trigger: 'blur' },
      ],
      awardtime: [
        { required: true, message: '请输入获奖时间', trigger: 'blur' },
      ],
      issuingunit: [
        { required: true, message: '请输入颁发单位', trigger: 'blur' },
      ],
      groupranking: [
        { required: true, message: '请输入中咨集团排名', trigger: 'blur' },
      ],
    })

    const ruleFormRef = ref()
    const ruleFormRef1 = ref()
    const submitForm = async () => {
      let val = false
      ruleFormRef.value.validate(valid => {
        if (valid) {
          val = true
        }
      })
      let val1 = false
      ruleFormRef1.value.validate(valid => {
        if (valid) {
          val1 = true
        }
      })
      if (!val1 || !val) {
        emit('valueFlag2', false)
      } else {
        emit('valueFlag2', true)
      }
    }

    // 移除标签调用
    const removeTag = (value) => {
      const item = findItemNested(data.selOp, value, 'children')
      let arr = ruleForm.classname.split(',')
      let arr1 = ruleForm.classid.split(',')
      let result = arr.indexOf(item.name)
      if (result > -1) {
        arr.splice(arr.indexOf(item.name), 1)
        arr1.splice(arr1.indexOf(item.id), 1)
      }
      ruleForm.classname = arr + ''
      ruleForm.classid = arr1 + ''
    }

    const chooseMatter = (value) => {
      let arr = [] as any
      ruleForm.classid = value.join(',')
      value.forEach(e =>{
        let o = findItemById(data.selOp,e)
        arr.push(o.name)
        data.mainValue.push(o.id)
      })
      ruleForm.classname = arr.join(',')
      // let arr = ruleForm.classname
      // let arr1 = ruleForm.classid
      // value.map((i) => {
      //   const item = findItemNested(selOp.value, i, 'children')
      //   let result = arr.indexOf(item.name)
      //   if (result > -1) {
      //     return;
      //   }
      //   arr = arr + ',' + item.name
      //   arr1 = arr1 + ',' + item.id
      // })
      // ruleForm.classname = arr
      // ruleForm.classid = arr1
    }

    function findItemById(list, id) {
      // 每次进来使用find遍历一次
      let res = list.find((item) => item.id == id);

      if (res) {
        return res;
      } else {
        for (let i = 0; i < list.length; i++) {
          if (list[i].children instanceof Array && list[i].children.length > 0) {
            res = findItemById(list[i].children, id);

            if (res) return res;
          }
        }

        return null;
      }
    };

    const removeTag1 = (value) => {
      const item = findItemNested(data.selOp, value, 'children')
      let arr = ruleForm.competitionclass.split(',')
      let arr1 = ruleForm.competitionclassid.split(',')
      let result = arr.indexOf(item.name)
      if (result > -1) {
        arr.splice(arr.indexOf(item.name), 1)
        arr1.splice(arr1.indexOf(item.id), 1)
      }
      ruleForm.competitionclass = arr + ''
      ruleForm.competitionclassid = arr1 + ''
    }

    const chooseMatter1 = (value) => {
      let arr = [] as any
      ruleForm.competitionclassid = value.join(',')
      value.forEach(e =>{
        let o = findItemById(data.selOp,e)
        arr.push(o.name)
        data.mainValue1.push(o.id)
      })
      ruleForm.competitionclass = arr.join(',')
      // let arr = ruleForm.competitionclass
      // let arr1 = ruleForm.competitionclassid
      // value.map((i) => {
      //   const item = findItemNested(selOp.value, i, 'children')
      //   let result = arr.indexOf(item.id)
      //   if (result > -1) {
      //     return;
      //   }
      //   arr = arr + ',' + item.name
      //   arr1 = arr1 + ',' + item.id
      // })
      // ruleForm.competitionclass = arr
      // ruleForm.competitionclassid = arr1

    }

    const findItemNested = (arr, itemId, nestingKey) => (
      arr.reduce((a, item) => {
        if (a) return a;
        if (item.id === itemId) return item;
        if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
      }, null)
    );

    const personForm = reactive({
      unit: '',
      unitid: '',
      joinusernameid: '',
      joinusername: '',
      role: '',
    }) as any

    const changeName = (item) => {
      personForm.joinusername = item.cname
      personForm.joinusernameid = item.userId
    }

    const changeUnit = (item) => {
      console.log(item)
      personForm.unit = item.name
      personForm.unitid = item.id
    }

    const changeRole = (item) => {
      console.log(item)
      // personForm.roleName = item.roleName
      personForm.role = item.roleName
    }
    //删除人员
    const deleteUser = (row) =>{
      console.log('row',row.id,usersList.value);
      let index = usersList.value.findIndex((e : any) =>{
        return e.id == row.id
      })
      usersList.value.splice(index,1)
    }
    const addPerson = () => {
      if (personForm.joinusername) {
        let obj = {
          unit: personForm.unit,
          unitid: personForm.unitid,
          joinusernameid: personForm.joinusernameid,
          joinusername: personForm.joinusername,
          role: personForm.role,
        }
        if (JSON.stringify(usersList.value).indexOf(JSON.stringify(obj)) == -1) {
          usersList.value.push(obj)
        } else {
          tips('不可添加相同成员', 'warning')
          return;
        }
        Object.keys(personForm).forEach((key) => {
          personForm[key] = ''
        })
        console.log(usersList)
        emit('usersChange', usersList)
      }
    }
    onMounted(() =>{
      nextTick(() =>{
       getOrgList()
      })
    })

    return {
      open,
      ruleForm,
      rules,
      ruleFormRef,
      ruleFormRef1,
      submitForm,
      labelPosition,
      data,
      options,
      usersList,
      personForm,
      mainValueRef,
      mainValueRef1,

      chooseMatter,
      removeTag,
      chooseMatter1,
      removeTag1,
      addPerson,

      changeName,
      changeUnit,
      changeRole,

      changeValue,
      changeValue1,
      changeValue2,
      changeValue3,
      changeValue4,
      changeValue5,
      changeValue6,
      changeValue7,
      deleteUser,
      deptForm,
    }
  },
}
</script>

<style lang="scss">
.gy-cascader{
  .el-cascader-node {
    max-width: 250px;
  }
}
</style>
<style lang="scss" scoped>
.personAddBtn {
  position: absolute;
  bottom: 0;
  right: 0;
}

.demo-form-inline .el-form-item {
  width: 48%;
}

:deep(.labelHeight .el-form-item__label) {
  line-height: 20px;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor.el-input__inner) {
  width: 100%;
}

:deep(.demo-form-inline .el-select) {
  width: 100%;
  margin: 0;
}

.el-select {
  width: 100%;
  margin: 0;
}

.selectLabel {
  width: 70%;
  min-height: 40px;
  line-height: 40px;
  padding: 0 15px;
  border: 1px solid #ccc;
  border-radius: 6px;
  display: inline-block;
}

.addLabel {
  display: inline-block;
  width: 120px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #169bd5;
  border-radius: 6px;
  color: #fff;
  margin-left: 15px;
}

.unitBox {
  width: 100%;
  margin: 30px 0;

  .title {
    padding: 15px 0;
    border-bottom: 1px solid #ccc;
  }

  .tagBox {
    line-height: 40px;
    margin-top: 15px;
    border: 1px solid #ccc;
    border-radius: 8px;
    padding: 10px 15px;
  }
}

.el-tag {
  margin-right: 10px;
}


.content-box {
  width: 250px;
  height: 33px;
  padding: 5px;
  box-sizing: border-box;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.select {
  color: #eee;
}

.align-center {
  align-items: center;
}

.space-between {
  justify-content: space-between;
}

.mt20 {
  margin-top: 20px;
}

.flex {
  display: flex;
}

.handle {
  position: absolute;
  top: 17px;
  right: 20px;
  display: flex;
  align-items: center;
}

.search-box {
  display: flex;
  justify-content: end;
  align-items: center;
  margin-bottom: 10px;
}
</style>
